package com.wichell.framework.dfs.factory;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.log4j.Logger;
import org.lokra.seaweedfs.core.FileSource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.StringUtils;

import com.wichell.framework.dfs.service.ResourceService;
import com.wichell.framework.dfs.service.WeedfsResouceServiceImpl;

public class ResourceFactoryBean implements FactoryBean<ResourceService> {

	private Logger logger = Logger.getLogger(ResourceFactoryBean.class);

	private ResourceInstanceMode mode;

	private ResourceService resourceService;

	private FileSource fileSource;

	@PostConstruct
	public void init() {
		if (logger.isDebugEnabled()) {
			logger.debug("初始化分布式锁模板");
		}
		switch (mode) {
		case WEEDFS: {
			resourceService = new WeedfsResouceServiceImpl(fileSource);
			break;
		}
		default: {
			resourceService = new WeedfsResouceServiceImpl(fileSource);
			break;
		}
		}
	}

	@PreDestroy
	public void destroy() {
		if (logger.isDebugEnabled()) {
			logger.debug("销毁分布式锁模板");
		}
		try {
			resourceService.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public ResourceService getObject() throws Exception {
		return resourceService;
	}

	@Override
	public Class<?> getObjectType() {
		return ResourceService.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	public void setMode(String mode) {
		if (StringUtils.isEmpty(mode)) {
			throw new IllegalArgumentException("未找到资源配置项");
		}
		this.mode = ResourceInstanceMode.parse(mode);
		if (this.mode == null) {
			throw new IllegalArgumentException("不支持的资源模式");
		}
	}

	public void setFileSource(FileSource fileSource) {
		this.fileSource = fileSource;
	}

	private enum ResourceInstanceMode {
		WEEDFS, FTP;

		public static ResourceInstanceMode parse(String name) {
			for (ResourceInstanceMode modeIns : ResourceInstanceMode.values()) {
				if (modeIns.name().equals(name.toUpperCase())) {
					return modeIns;
				}
			}
			return null;
		}
	}
}